﻿using System;
using System.Configuration;
using System.IO;
using System.Text;
using System.Xml;

using Rarous.TexyNet.Parser.Elements;

namespace Rarous.TexyNet.Parser.Formatter {
  public class XhtmlFormatter : TexyFormatter<String> {
    public const string TexyNetSign = "<!-- Texy.net -->";

    private ITexySettings _configElement;

    public override ITexySettings Configuration {
      get {
        return _configElement;
      }
      set {
        _configElement = value;
      }
    }

    public override string Format() {
      StringBuilder sb = new StringBuilder();
      Format(sb, Root ?? new Element());
      sb.Append(Environment.NewLine + TexyNetSign);
      return sb.ToString().Trim();
    }

    private static void Format(StringBuilder sb, Element element) {
      if (element.ChildElements.Count > 0) {
        foreach (Element el in element.ChildElements) {
          Format(sb, el);
        }
      }
      else {
        using (StringWriter sw = new StringWriter(sb)) {
          using (XmlWriter writer = new XmlTextWriter(sw)) {
            switch (element.ElementType) {
              case ElementType.Paragraph:
                writer.WriteElementString("p", element.Text);
                break;
              default:
                writer.WriteString(element.Text);
                break;
            }
          }
        }
      }
    }
  }
}